package com.cn.yunhe.rentcars.web;

import java.util.Date;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cn.yunhe.rentcars.mapper.AccountMapper;
import com.cn.yunhe.rentcars.model.Account;
@Controller
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Value(value = "${application.message}")
    private String message;
    @Autowired
	private AccountMapper accountMapper;
    @RequestMapping("/")
	public String showlogin() {
		//System.out.println("进入用户校验");
		//当页面输入 / 请求时就调转到登录页面。		
		return "login.html";
	}
	
    @RequestMapping(value = "/loginvalid", method=RequestMethod.POST)
    public String login(Map<String, Object> model, @RequestParam("username") String username,
                        @RequestParam("password") String password) {
    	//System.out.println("验证用户名和密码");
    	//System.out.println("用户名："+username+" 密码："+password);
    	//当页面点击提交按钮后 提交到本方法。将用户名和密码传递进来。
    	//实例化 UsernamePasswordToken ，该类会调用shiro 自己定义的shiroRealmImpl，进行用户校验。
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        /**
         * Subject：主体，代表了当前“用户”，这个用户不一定是一个具体的人，
         * 与当前应用交互的任何东西都是Subject，如网络爬虫，机器人等；即一个抽象概念；
         * 所有Subject都绑定到SecurityManager，与Subject的所有交互都会委托给SecurityManager；
         * 可以把Subject认为是一个门面；SecurityManager才是实际的执行者；
         */
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException uae) {
            logger.info("未知账户");
        } catch (IncorrectCredentialsException ice) {
            logger.info("密码不正确");
        } catch (LockedAccountException lae) {
            logger.info("账户已锁定");
        } catch (ExcessiveAttemptsException eae) {
            logger.info("用户名密码次数过多");
        } catch (AuthenticationException ae) {
            logger.info("用户名密码不正确");
        }

        if (subject.isAuthenticated()) {
            logger.info("登录认证通过");
            model.put("time", new Date());
            model.put("message", this.message);
            model.put("username", username);
            Account ac = accountMapper.getAccountRole(username);
            //传递一个session 将用户名字持续显示到页面上。供后续其他地方使用。
            subject.getSession().setAttribute("username", username);  
            subject.getSession().setAttribute("rolename", ac.getRolename());
            subject.getSession().setAttribute("modelT", model);
            return "redirect:/home";
        } else {
            usernamePasswordToken.clear();
            return "redirect:/";
        }
    }
    @RequestMapping(value="/logout", method=RequestMethod.GET)
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }
}
